<?php

class APIEmployee extends ApiBaseClass {

    public function __construct() {
        parent::_init();
    }

    public $employeeService = null;

    private $newHeight = 0, $newWidth = 0;

    public function editAction() {

    }

    public function updateAction() {

        /**
         personal[_csrf_token]: 7d29e246668bd62348d9b1776f3f1c37
         personal[txtEmpID]: 4
         personal[txtEmpFirstName]: D
         personal[txtEmpMiddleName]: D
         personal[txtEmpLastName]: D
         personal[txtEmployeeId]: 0004
         personal[txtOtherID]:
         personal[txtLicenNo]:
         personal[txtLicExpDate]: yyyy-mm-dd
         personal[optGender]: 1
         personal[optGender]: 2
         personal[cmbMarital]:
         personal[cmbNation]: 0
         personal[DOB]: yyyy-mm-dd
         */
        $loggedInEmpNum = $this -> _context -> getUser() -> getEmployeeNumber();

        $personal = $this -> _request -> getParameter('personal');
        $empNumber = (isset($personal['txtEmpID'])) ? $personal['txtEmpID'] : $this -> _request -> getParameter('id');
        // $this -> empNumber = $empNumber;

        // TODO: Improve
        $adminMode = $this -> _context -> getUser() -> hasCredential(Auth::ADMIN_ROLE);

        $personalInformationPermission = $this -> getDataGroupPermissions('personal_information', $empNumber);
        $canEditSensitiveInformation = ($empNumber != $loggedInEmpNum) || $adminMode;

        $param = array('empNumber' => $empNumber, 'personalInformationPermission' => $personalInformationPermission, 'canEditSensitiveInformation' => $canEditSensitiveInformation);

        // TODO : outhorization implementation here

        if (!$this -> IsActionAccessible($empNumber)) {
            //$this -> forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
            return;
        }
        $this -> setForm(new EmployeePersonalDetailsForm( array(), $param, true));
        if ($this -> personalInformationPermission -> canUpdate()) {
            $this -> form -> bind($this -> _request -> getParameter($this -> form -> getName()));
            if ($this -> form -> isValid()) {

                $this -> _checkWhetherEmployeeIdExists($this -> form -> getValue('txtEmployeeId'), $empNumber);

                $employee = $this -> form -> getEmployee();
                $this -> getEmployeeService() -> saveEmployee($employee);
                $this -> _data['response'] = $employee -> getData();
            }
        }
    }

    public function showAction() {

        $loggedInEmpNum = $this -> _context -> getUser() -> getEmployeeNumber();

        $personal = $this -> _request -> getParameter('personal');
        $empNumber = (isset($personal['txtEmpID'])) ? $personal['txtEmpID'] : $this -> _request -> getParameter('id');
        // $this -> empNumber = $empNumber;

        // TODO: Improve
        $adminMode = $this -> _context -> getUser() -> hasCredential(Auth::ADMIN_ROLE);

        $personalInformationPermission = $this -> getDataGroupPermissions('personal_information', $empNumber);
        $canEditSensitiveInformation = ($empNumber != $loggedInEmpNum) || $adminMode;

        $param = array('empNumber' => $empNumber, 'personalInformationPermission' => $personalInformationPermission, 'canEditSensitiveInformation' => $canEditSensitiveInformation);

        // TODO : outhorization implementation here

        if (!$this -> IsActionAccessible($empNumber)) {
            //$this -> forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
            return;
        }

        $showDeprecatedFields = OrangeConfig::getInstance() -> getAppConfValue(ConfigService::KEY_PIM_SHOW_DEPRECATED);
        $showSSN = OrangeConfig::getInstance() -> getAppConfValue(ConfigService::KEY_PIM_SHOW_SSN);
        $showSIN = OrangeConfig::getInstance() -> getAppConfValue(ConfigService::KEY_PIM_SHOW_SIN);

        $this -> setForm(new EmployeePersonalDetailsForm( array(), $param, true));
        $employee = $this -> form -> getEmployee();

        $this -> _data['response'] = $employee -> getData();

    }

    public function listAction() {

        $empNumber = $this -> _request -> getParameter('empNumber');
        $isPaging = $this -> _request -> getParameter('hdnAction') == 'search' ? 1 : $this -> _request -> getParameter('pageNo', 1);

        $pageNumber = $isPaging;
        if (!empty($empNumber) && $this -> _context -> getUser() -> hasAttribute('pageNumber')) {
            $pageNumber = $this -> _context -> getUser() -> getAttribute('pageNumber');
        }

        $noOfRecords = sfConfig::get('app_items_per_page');

        $offset = ($pageNumber >= 1) ? (($pageNumber - 1) * $noOfRecords) : ($this -> _request -> getParameter('pageNo', 1) - 1) * $noOfRecords;

        $this -> form = new EmployeeSearchForm($this -> getFilters());
        // if ($request->isMethod('post')) {
        //
        // $this->form->bind($request->getParameter($this->form->getName()));
        //
        // if ($this->form->isValid()) {
        //
        // if($this->form->getValue('isSubmitted')=='yes'){
        // $this->setSortParameter(array("field"=> NULL, "order"=> NULL));
        // }
        //
        // $this->setFilters($this->form->getValues());
        //
        // } else {
        // $this->setFilters(array());
        // }
        //
        // $this->setPage(1);
        // }

        $sort = array("field" => $this->_request -> getParameter('sortField'), "order" => $this->_request -> getParameter('sortOrder'));
        $this -> setPage(1);

        $sortField = $sort["field"];
        $sortOrder = $sort["order"];
        $filters = $this -> getFilters();

        if (isset($filters['employee_name'])) {
            $filters['employee_name'] = str_replace(' (' . __('Past Employee') . ')', '', $filters['employee_name']['empName']);
        }

        if (isset($filters['supervisor_name'])) {
            $filters['supervisor_name'] = str_replace(' (' . __('Past Employee') . ')', '', $filters['supervisor_name']);
        }

        $filterApply = !empty($filters);
        $accessibleEmployees = APIUserRoleManagerFactory::getUserRoleManager() -> getAccessibleEntityIds('Employee');

        if (count($accessibleEmployees) > 0) {
            $filters['employee_id_list'] = $accessibleEmployees;
            $count = $this -> getEmployeeService() -> getSearchEmployeeCount($filters);

            $parameterHolder = new EmployeeSearchParameterHolder();
            $parameterHolder -> setOrderField($sortField);
            $parameterHolder -> setOrderBy($sortOrder);
            $parameterHolder -> setLimit($noOfRecords);
            $parameterHolder -> setOffset($offset);
            $parameterHolder -> setFilters($filters);
            $list = $this -> getEmployeeService() -> searchEmployees($parameterHolder);
        } else {
            $count = 0;
            $list = array();
        }

        $this->_data['response'] = $list->toArray() ;


    }

    public function updateAttachmentAction() {
        $loggedInEmpNum = $this -> _context -> getUser() -> getEmployeeNumber();
        $loggedInUserName = $this -> _context -> getUser() -> getAttribute('firstName');

        $this -> form = new EmployeeAttachmentForm( array(), array('loggedInUser' => $loggedInEmpNum, 'loggedInUserName' => $loggedInUserName), true);

        if ($this -> _request -> isMethod('post')) {

            $attachId = $this -> _request -> getParameter('seqNO');
            $screen = $this -> _request -> getParameter('screen');

            $permission = $this -> getDataGroupPermissions($screen . '_attachment', $this -> _request -> getParameter('id'));

            if ((empty($attachId) && $permission -> canCreate()) || (!empty($attachId) && $permission -> canUpdate())) {

                // Handle the form submission
                $this -> form -> bind($this -> _request -> getPostParameters(), $this -> _request -> getFiles());

                if ($this -> form -> isValid()) {

                    $empNumber = $this -> form -> getValue('id');
                    if (!$this -> IsActionAccessible($empNumber)) {
                        //$this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
                        return;
                    }

                    $this -> form -> save();
                    // $this->getUser()->setFlash('listAttachmentPane.success', __(TopLevelMessages::SAVE_SUCCESS));
                } else {

                    // $validationMsg = '';
                    // foreach ($this->form->getWidgetSchema()->getPositions() as $widgetName) {
                    // if ($this->form[$widgetName]->hasError()) {
                    // $validationMsg .= __(TopLevelMessages::FILE_SIZE_SAVE_FAILURE);
                    // }
                    // }

                    $this -> _data['message'] = "Error saving files";
                    $this -> _data['errors'] = 1;

                    // $this->getUser()->setFlash('saveAttachmentPane.warning',$validationMsg);
                    // $this->getUser()->setFlash('attachmentComments', $request->getParameter('txtAttDesc'));
                    // $this->getUser()->setFlash('attachmentSeqNo', $request->getParameter('seqNO'));
                }
            } else {
                // $this->forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
                $this -> _data['message'] = "Permission not enough";
                $this -> _data['errors'] = 1;
            }
        }

    }

    /**
     *
     *
     * contact[_csrf_token]: a988e522c31c81ecb9d5f0824ace308f
     contact[empNumber]: 4
     contact[street1]:
     contact[street2]:
     contact[city]:
     contact[province]:
     contact[state]:
     contact[emp_zipcode]:
     contact[country]: 0
     contact[emp_hm_telephone]:
     contact[emp_mobile]:
     contact[emp_work_telephone]:
     contact[emp_work_email]:
     contact[emp_oth_email]:
     */

    public function updateContactDetailAction() {
        $loggedInEmpNum = $this -> _context -> getUser() -> getEmployeeNumber();

        $contact = $this -> _request -> getParameter('contact');
        $empNumber = (isset($contact['empNumber'])) ? $contact['empNumber'] : $request -> getParameter('id');

        $contactDetailsPermission = $this -> getDataGroupPermissions('contact_details', $empNumber);

        if (!$this -> IsActionAccessible($empNumber)) {
            //$this -> forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));
            return;
        }

        $param = array('empNumber' => $empNumber, 'contactDetailsPermission' => $contactDetailsPermission);
        $this -> setForm(new EmployeeContactDetailsForm( array(), $param, true));

        if ($contactDetailsPermission -> canUpdate()) {

            $this -> form -> bind($this -> _request -> getParameter($this -> form -> getName()));
            if ($this -> form -> isValid()) {
                $employee = $this -> form -> getEmployee();
                $this -> getEmployeeService() -> saveEmployee($employee);
                $this -> _data['response'] = $employee -> getData();
            }
        } else {
            $this -> _data['errors'] = 1;
            $this -> _data['message'] = "Permission not enough";

        }
    }

    public function viewMyLeaveEntilement() {

    }

    protected function _checkWhetherEmployeeIdExists($employeeId, $empNumber) {

        if (!empty($employeeId)) {

            $employee = $this -> getEmployeeService() -> getEmployeeByEmployeeId($employeeId);

            if (($employee instanceof Employee) && trim($employee -> getEmpNumber()) != trim($empNumber)) {
                $this -> getUser() -> setFlash('templateMessage', array('warning', __('Employee Id Exists')));
                $this -> redirect('pim/viewPersonalDetails?empNumber=' . $empNumber);
            }

        }

    }

    public function getDataGroupPermissions($dataGroups, $empNumber) {
        $loggedInEmpNum = $this -> _context -> getUser() -> getEmployeeNumber();

        $entities = array('Employee' => $empNumber);
        $self = $empNumber == $loggedInEmpNum;

        return $this -> _context -> getUserRoleManager() -> getDataGroupPermissions($dataGroups, array(), array(), $self, $entities);
    }

    protected function getFilters() {
        return $this -> _context->getUser() -> getAttribute('emplist.filters', null, 'pim_module');
    }

    protected function setPage($page) {
        $this->_context->getUser()->setAttribute('emplist.page', $page, 'pim_module');
    }

}
?>